package top.pmwly.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName CorsConfig.java
 * @Description 跨域解决方案
 * @createTime 2021年09月22日 19:34:00
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    /**
     * 跨域解决
     * @return
     */
    private CorsConfiguration buidldConfig(){
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        //所有地址可以访问
        corsConfiguration.addAllowedOrigin("*");
        //跨域请求头
        corsConfiguration.addAllowedHeader("*");
        //跨域请求方法
        corsConfiguration.addAllowedMethod("*");
        //corsConfiguration.addExposedHeader("Authorization");
        //跨域可以携带cookie
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buidldConfig());
        return new CorsFilter(source);
    }
    @Override
    public void addCorsMappings(CorsRegistry corsRegistry){
        corsRegistry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .maxAge(3600)
                .allowedHeaders("*");
    }

}
